/**
 * @file 基础服务
 * @module models/version
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires libs/storgae - 本地存储工具
 * @requires config/topic - 主题配置
 * @requires models/music - 音乐模型
 * @requires models/story - 故事模型
 */
import storage from '../libs/storage';
import { TOPIC } from '../config/topic';
import musicModel from './music';
import storyModel from './story';

/**
 * @description 获取版本号
 * @returns {promise} 
 */
const getVersion = () => {
  return wx.cloud.callFunction({
    name: 'service',
    data: {
      action: 'version'
    }
  });
}

/**
 * @description 获取祝福语
 * @returns {promise} 
 */
const getBlessingWords = () => {
  return wx.cloud.callFunction({
    name: 'service',
    data: {
      action: 'blessing'
    }
  });
}

/**
 * @description 收藏主题
 * @param {string} collectType - 收藏类型 
 * @param {string} operation - 操作类型 
 * @param {object} params - 参数
 * @returns {promise}
 */
const collect = (collectType, operation, params) => {
  const { openid } = storage.get('user');

  return wx.cloud.callFunction({
    name: 'service',
    data: {
      action: 'collect',
      data: { 
        collectType,
        operation,
        openid,
        params
      }
    }
  });
}

/**
 * @description 查询收藏状态
 * @param {string} collectType - 收藏类型 
 * @param {string} id - 主题ID
 * @returns {promise}
 */
const getCollectStatus = (collectType, id) => {
  const { openid } = storage.get('user');

  return wx.cloud.callFunction({
    name: 'service',
    data: {
      action: 'queryCollectStatus',
      data: { 
        collectType,
        openid,
        id
      }
    }
  });
}

/**
 * @description 获取收藏集
 * @returns {promise}
 */
const getCollectList = async () => {
  const { openid } = storage.get('user');

  const { result: { data } } = await wx.cloud.callFunction({
    name: 'service',
    data: {
      action: 'queryCollectList',
      data: { 
        openid
      }
    }
  }); 

  if (data.collect) {
    const { single, topic } = data.collect;

    // 主题列表处理
    const topicList = await Promise.all(topic.map(item => {
      return (item.topic === TOPIC.MUSIC) ? musicModel.getTopicDetail(item.id) 
                                         : storyModel.getTopicDetail(item.type, item.id)
    }));

    return {
      single,
      topic: topicList.map((item, index) => {
        const { title, tags, coverImgUrl } = item.result.data;

        return Object.assign(topic[index], {
          title,
          tags,
          coverImgUrl
        });
      }),
    }
  }
  
  return {
    single: [],
    topic: []
  };
}

// 导出功能集合
export default {
  getVersion,
  getBlessingWords,
  collect,
  getCollectStatus,
  getCollectList
}